using System;
using System.Globalization;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Business;
using mojoPortal.Web;
using mojoPortal.Web.UI;
using mojoPortal.Web.Framework;
using Resources;


namespace ud_Gallery.UI
{
	
	public partial class GalleryControl : SiteModuleControl
    {
        #region Properties 

        protected string EditContentImage = WebConfigSettings.EditContentImage;
        private Literal imageLink;
        private Gallery gallery;
        private GalleryConfiguration config = new GalleryConfiguration();
        private string imageFolderPath;
        private int thumbsPerPage = 999;
        private int itemId = -1;
        private const string ViewImagePage = "GalleryBrowse.aspx";
        private int totalRows;
	    private string baseUrl = string.Empty;
        protected string thumnailBaseUrl = string.Empty;
        protected string webSizeBaseUrl = string.Empty;
        protected string fullSizeBaseUrl = string.Empty;
        
        
        protected int PageNumber
        {
            get
            {
                object o = ViewState["PageNumber"];
                if (o != null)
                {
                    return Convert.ToInt32(o);
                }
                return 1;
            }
            set
            {
                ViewState["PageNumber"] = value;
                
            }
        }

        protected int TotalPages
        {
            get
            {
                object o = ViewState["TotalPages"];
                if (o != null)
                {
                    return Convert.ToInt32(o);
                }
                return 1;
            }
            set
            {
                ViewState["TotalPages"] = value;

            }
        }

        protected bool UseLightboxMode
        {
            get
            {
                object o = ViewState["UseLightboxMode"];
                if (o != null)
                {
                    return Convert.ToBoolean(o);
                }
                return true;
            }
            set
            {
                ViewState["UseLightboxMode"] = value;
            }
        }




        protected bool UseCompactMode
        {
            get
            {
                object o = ViewState["UseCompactMode"];
                if (o != null)
                {
                    return Convert.ToBoolean(o);
                }
                return false;
            }
            set
            {
                ViewState["UseCompactMode"] = value;

            }
        }

        #endregion

		protected void Page_Load(object sender, EventArgs e)
		{
            LoadSettings();

            if (config.UseSlideShow)
            {
                SetupSilverlight();
            }
            else
            {

                if (!Page.IsPostBack)
                {
                    PopulateControls();
                }
            }
		}

        private void SetupSilverlight()
        {
            pnlSilverlight.Visible = true;
            pnlMain.Visible = false;
            slideShow.XmlDataUrl = SiteRoot + "/Services/GalleryDataService.ashx?pageid=" + PageId.ToInvariantString()
                        + "&amp;mid=" + ModuleId.ToInvariantString();

            slideShow.Theme = config.SlideShowTheme;
            slideShow.Height = config.SlideShowHeight;
            slideShow.Width = config.SlideShowWidth;
            slideShow.Windowless = config.SlideShowWindowlessMode;
        }

        private void PopulateControls()
        {
            pager.CurrentIndex = 1;
            pagerTop.CurrentIndex = 1;
            BindRepeater();
            BindImage();
        }

        private void BindRepeater()
        {
            DataTable dt = gallery.GetThumbsByPage(PageNumber, thumbsPerPage);

            if (dt.Rows.Count > 0)
            {
                TotalPages = Convert.ToInt32(dt.Rows[0]["TotalPages"]);
                itemId = Convert.ToInt32(dt.Rows[0]["ItemID"]);
                totalRows = thumbsPerPage * TotalPages;
            }

            //this handles issue: when redirected back to page from edit page
            //if you deleted the last image on the page an error occurs
            //so decrement the pageNumber
            while (PageNumber > TotalPages)
            {
                PageNumber -= 1;

                dt = gallery.GetThumbsByPage(PageNumber, thumbsPerPage);
                if (dt.Rows.Count > 0)
                {
                    TotalPages = Convert.ToInt32(dt.Rows[0]["TotalPages"]);
                    itemId = Convert.ToInt32(dt.Rows[0]["ItemID"]);
                }
            }

            if (TotalPages > 1)
            {
                if (RenderInWebPartMode)
                {
                    if (totalRows > thumbsPerPage)
                    {
                        Literal moreLink = new Literal
                                               {
                                                   Text = @"<a href='"
                                                          + SiteRoot
                                                          + @"/" + ViewImagePage
                                                          + @"?ItemID=" + itemId.ToInvariantString()
                                                          + @"&amp;mid=" + ModuleId.ToInvariantString()
                                                          + @"&amp;pageid=" + PageId.ToInvariantString()
                                                          + @"&amp;pagenumber=" + PageNumber.ToInvariantString()
                                                          + @"'>" + GalleryResources.GalleryWebPartMoreLink
                                                          + @"</a>"
                                               };

                        pnlGallery.Controls.Add(moreLink);
                        pager.Visible = false;
                        pagerTop.Visible = false;
                    }

                }
                else
                {
                    pager.ShowFirstLast = true;
                    pager.PageSize = thumbsPerPage;
                    pager.PageCount = TotalPages;
                    pagerTop.ShowFirstLast = true;
                    pagerTop.PageSize = thumbsPerPage;
                    pagerTop.PageCount = TotalPages;
                }
            }
            else
            {
                pager.Visible = false;
                pagerTop.Visible = false;
            }

            
            if (UseLightboxMode)
            {
                if (GalleryConfiguration.UseGreybox)
                {
                    SetupImageArray(dt);
                }
                else
                {
                    SetupColorbox();
                }
            }

            rptGallery.DataSource = dt;
            rptGallery.DataBind();

        }

        private void SetupImageArray(DataTable dt)
        {
            if (dt == null) { return; }
            if (dt.Rows.Count == 0) { return; }

            StringBuilder script = new StringBuilder();

            script.Append("var imset" + ModuleId.ToString(CultureInfo.InvariantCulture) + " = [");
            string comma = string.Empty;

            foreach (DataRow row in dt.Rows)
            {

                script.Append(comma);
                script.Append("{'caption':'");
                script.Append(Server.HtmlEncode(row["Caption"].ToString()).HtmlEscapeQuotes());
                script.Append("','url':'");
                script.Append(ImageSiteRoot + webSizeBaseUrl);
                script.Append(row["WebImageFile"].ToString());
                script.Append("'");
                script.Append("}");

                comma = ",";

            }

            script.Append("];");

            gbLauncher.Visible = true;
            gbLauncher.NavigateUrl = Request.RawUrl;
            gbLauncher.ToolTip = GalleryResources.LaunchGalleryLink;
            gbLauncher.ClientClick = "return GB_showImageSet(imset" + ModuleId.ToInvariantString() + ", 1)";

            
            ScriptManager.RegisterClientScriptBlock(Page, typeof(Page),
                    "img" + ModuleId.ToInvariantString(), "\n<script type=\"text/javascript\">\n"
                    + script
                    + "\n</script>", false);
          
        }

        private void SetupColorbox()
        {
            StringBuilder script = new StringBuilder();

            script.Append("$(document).ready(function() {");
            script.Append("$(\"a[rel='cbg");
            script.Append(ModuleId.ToInvariantString());
            script.Append("']\").colorbox(");

            script.Append("{");

            script.Append("current: \"" + GalleryResources.ImageCountJsFormat + "\"");
            script.Append(",previous: \"" + GalleryResources.Previous + "\"");
            script.Append(",next: \"" + GalleryResources.Next + "\"");
            script.Append(",close: \"" + GalleryResources.Close + "\"");

            if (config.ColorBoxTransition != GalleryConfiguration.ColorBoxDefaultTransition)
            {
                script.Append(",transition:\"" + config.ColorBoxTransition + "\"");
            }

            if (config.ColorBoxTransitionSpeed != GalleryConfiguration.ColorBoxDefaultTransitionSpeed)
            {
                script.Append(",speed:" + config.ColorBoxTransitionSpeed);
            }

            script.Append(",opacity:" + config.ColorBoxOpacity);
           
            if (config.ColorBoxUseSlideshow != GalleryConfiguration.ColorBoxDefaultUseSlideShow)
            {
                script.Append(",slideshow:" + config.ColorBoxUseSlideshow.ToString().ToLower());
            }

            if (config.ColorBoxUseSlideshow)
            {
                script.Append(",slideshowSpeed: " + config.ColorBoxSlideshowSpeed);
                
                if (config.ColorBoxSlideshowAuto != GalleryConfiguration.ColorBoxDefaultUseSlideShow)
                {
                    script.Append(",slideshowAuto: " + config.ColorBoxSlideshowAuto.ToString().ToLower());
                }

                script.Append(",slideshowStart: \"" + GalleryResources.StartSlideShow + "\"");
                script.Append(",slideshowStop: \"" + GalleryResources.StopSlideShow + "\"");
            }

            script.Append("}");

            script.Append(");");
            script.Append("});");

            ScriptManager.RegisterClientScriptBlock(Page, typeof(Page),
                    "img" + ModuleId.ToInvariantString(), "\n<script type=\"text/javascript\">\n"
                    + script
                    + "\n</script>", false);
        }
        

        private void BindImage()
        {
            if (!UseCompactMode) { return; }
            if (itemId == -1) { return; }

            imageLink = new Literal();
           
            GalleryImage galleryImage = new GalleryImage(ModuleId, itemId, imageFolderPath);

            imageLink.Text = @"<a onclick=""window.open(href,'_blank');return false;""  "
                + @" title=""" + Server.HtmlEncode(GalleryResources.GalleryWebImageAltText).HtmlEscapeQuotes()
                + @""" href=""" + ImageSiteRoot
                + fullSizeBaseUrl
                + galleryImage.ImageFile + @""" ><img src="""
                + ImageSiteRoot
                + webSizeBaseUrl
                + galleryImage.WebImageFile + @""" alt="""
                + Server.HtmlEncode(GalleryResources.GalleryWebImageAltText).HtmlEscapeQuotes() + @""" /></a>";

            
            pnlGallery.Controls.Clear();
            pnlGallery.Controls.Add(imageLink);
            lblCaption.Text = Page.Server.HtmlEncode(galleryImage.Caption);
            lblDescription.Text = galleryImage.Description;

            if ((config.ShowTechnicalData) && (galleryImage.MetaDataXml.Length > 0))
            {
                xmlMeta.DocumentContent = galleryImage.MetaDataXml;
                string xslPath = HttpContext.Current.Server.MapPath(WebUtils.GetApplicationRoot() + "/ImageGallery/GalleryMetaData.xsl");
                xmlMeta.TransformSource = xslPath;

            }
            
        }

        

        void rptGallery_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "setimage":
                    itemId = Convert.ToInt32(e.CommandArgument);
                    BindImage();
                    BindRepeater();
                    upGallery.Update();
                    break;
            }

        }

        protected void pager_Command(object sender, CommandEventArgs e)
        {
            PageNumber = Convert.ToInt32(e.CommandArgument);
            pager.CurrentIndex = PageNumber;
       
            BindRepeater();
            BindImage();

            upGallery.Update();
        }

       
        

        private int imageArrayIndex = 1;

        

        public String GetThumnailImageLink(
            String imageId,
            String thumbnailFile,
            String webImageFile,
            String caption)
        {
            
            String link = string.Empty;

            if (UseLightboxMode)
            {
                if(GalleryConfiguration.UseGreybox)
                {
                    link = "<a onclick='return GB_showImageSet(imset" + ModuleId.ToInvariantString() + "," + imageArrayIndex.ToInvariantString() + ")' "
                        + "title=\"" + Server.HtmlEncode(caption).HtmlEscapeQuotes()
                        + "\" href=\""
                        + ImageSiteRoot + webSizeBaseUrl
                        + webImageFile + "\">"
                        + GetThumnailMarkup(thumbnailFile, caption)
                        + "</a>";

                    imageArrayIndex++;
                }
                else
                {
                    link = "<a rel='cbg" + ModuleId.ToInvariantString() + "' "
                        + "title=\"" + Server.HtmlEncode(caption).HtmlEscapeQuotes()
                        + "\" href=\""
                        + ImageSiteRoot + webSizeBaseUrl
                        + webImageFile + "\">"
                        + GetThumnailMarkup(thumbnailFile, caption)
                        + "</a>";
                }

            }

            return link;


        }

        //protected String GetFullSizeUrl(String imageFile)
        //{
        //    //return GetImageRoot() + "/FullSizeImages/" + imageFile;
        //    return GetImageRoot() + "/WebImages/" + imageFile;

        //}

        protected String GetThumnailUrl(String thumbnailFile)
        {
            return ImageSiteRoot + thumnailBaseUrl + thumbnailFile;

        }

        protected String GetThumnailMarkup(String thumbnailFile, String caption)
        {
            return "<img  src=\"" + ImageSiteRoot + thumnailBaseUrl
                + thumbnailFile + "\" alt=\"" + Server.HtmlEncode(caption).HtmlEscapeQuotes() + "\" />";

        }

        private void LoadSettings()
        {
            gallery = new Gallery(ModuleId);
            try
            {
                // this keeps the action from changing during ajax postback in folder based sites
                SiteUtils.SetFormAction(Page, Request.RawUrl);
            }
            catch (MissingMethodException)
            {
                //this method was introduced in .NET 3.5 SP1
            }

            Title1.EditUrl = SiteRoot + "/ImageGallery/EditImage.aspx";
            Title1.EditText = GalleryResources.GalleryAddImageLabel;

            config = new GalleryConfiguration(Settings);

            if (IsEditable)
            {
                Title1.LiteralExtraMarkup = "&nbsp;<a href='"
                        + SiteRoot
                        + "/ImageGallery/BulkUpload.aspx?pageid=" + PageId.ToInvariantString()
                        + "&amp;mid=" + ModuleId.ToInvariantString()
                        + "' class='ModuleEditLink' title='" + GalleryResources.BulkUploadLink + "'><img src='/Data/Icon16x16/Upload.png' alt='"
                        + GalleryResources.BulkUploadLink + " |'</img></a>";
            }

            if (ModuleConfiguration != null)
            {
                Title = ModuleConfiguration.ModuleTitle;
                Description = ModuleConfiguration.FeatureName;
            }


            if (config.CustomCssClass.Length > 0) { pnlWrapper.CssClass += " " + config.CustomCssClass; }

            if (WebConfigSettings.ImageGalleryUseMediaFolder)
            {
                baseUrl = "/Data/Sites/" + siteSettings.SiteId.ToInvariantString() + "/media/GalleryImages/" + ModuleId.ToInvariantString() + "/";
            }
            else
            {
                baseUrl = "/Data/Sites/" + siteSettings.SiteId.ToInvariantString() + "/GalleryImages/" + ModuleId.ToInvariantString() + "/";
            }

            thumnailBaseUrl = baseUrl + "Thumbnails/";
            webSizeBaseUrl = baseUrl + "WebImages/";
            fullSizeBaseUrl = baseUrl + "FullSizeImages/";

            imageFolderPath = HttpContext.Current.Server.MapPath("~" + baseUrl);
            thumbsPerPage = config.ThumbsPerPage;
            UseCompactMode = config.UseCompactMode;

            if (RenderInWebPartMode)
            {
                UseCompactMode = false;
                thumbsPerPage = 6;
            }

            if (UseCompactMode)
            {
                UseLightboxMode = false;
                pnlImageDetails.Visible = false;
            }
            else
            {
                UseLightboxMode = true; 
            }

        }

        private void SetupColorboxInit()
        {
            Page.ClientScript.RegisterClientScriptBlock(typeof(Page),
                     "jqcolorbox", "\n<script src=\""
                     + Page.ResolveUrl("~/ClientScript/colorbox/jquery.colorbox-min.js") + "\" type=\"text/javascript\"></script>");

        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            SetupColorboxInit();
            Load += Page_Load;
            pager.Command += pager_Command;
            pagerTop.Command += pager_Command;
            rptGallery.ItemCommand += rptGallery_ItemCommand;
            if (WebConfigSettings.DisablePageViewStateByDefault) {Page.EnableViewState = true; }
        }

    }
}
